﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using YonYou.U8.IN.Forms;
using U8Login;
namespace Yonyou.U8.QuickImport
{
    public partial class DataImportDesign2 : ControlBase
    {
        private Hashtable _Cache;
        public DataImportDesign2(Context context) : base(context)
        {
            InitializeComponent();
            this.Initialize();
            this.InitHeaderCheckBox();
            InitializeModelView();
            InitializeImportStrategy();
            InitializeVourcherView();
            AdjustEnableState(ActionTiming.Init, cBoxSolution.Checked);
            InitializeEventHandler();
        }

        private void Initialize()
        {
            this._Cache = new Hashtable();
        }

        private DataTable _table;
        private CheckBox headerCheckBox;

        private void InitHeaderCheckBox()
        {
            if (!base.DesignMode)
            {
                this.headerCheckBox = new CheckBox();
                this.headerCheckBox.Size = new Size(15, 15);
                this.headerCheckBox.Enabled = true;
                this.headerCheckBox.BackColor = Color.FromArgb(237, 237, 237);
                this.itemGrid.Controls.Add(this.headerCheckBox);
                this.headerCheckBox.KeyUp += this.HeaderCheckBox_KeyUp;
                this.headerCheckBox.MouseClick += this.HeaderCheckBox_MouseClick;
                this.itemGrid.CurrentCellDirtyStateChanged += this.ItemGridSelectAll_CurrentCellDirtyStateChanged;
                this.itemGrid.CellPainting += this.ItemGridSelectAll_CellPainting;
            }
        }

        private void HeaderCheckBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                this.HeaderCheckBoxClick((CheckBox)sender);
            }
        }

        private void HeaderCheckBox_MouseClick(object sender, MouseEventArgs e)
        {
            this.HeaderCheckBoxClick((CheckBox)sender);
        }

        private void ItemGridSelectAll_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == 0)
            {
                this.ResetHeaderCheckBoxLocation(e.ColumnIndex, e.RowIndex);
            }
        }

        private void ResetHeaderCheckBoxLocation(int ColumnIndex, int RowIndex)
        {
            Rectangle cellDisplayRectangle = this.itemGrid.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);
            Point location = default(Point);
            location.X = cellDisplayRectangle.Location.X + (cellDisplayRectangle.Width - this.headerCheckBox.Width) / 2 + 1;
            location.Y = cellDisplayRectangle.Location.Y + (cellDisplayRectangle.Height - this.headerCheckBox.Height) / 2 + 1;
            this.headerCheckBox.Location = location;
        }

        private void HeaderCheckBoxClick(CheckBox headerCheckBox)
        {
            for (int i = 0; i < this._table.Rows.Count; i++)
            {
                this._table.Rows[i]["Selected"] = headerCheckBox.Checked;
            }
            this.itemGrid.RefreshEdit();
            this.itemGrid.Refresh();
        }

        private void ItemGridSelectAll_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.itemGrid.CurrentCell is DataGridViewCheckBoxCell)
            {
                this.itemGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        protected XDocument VourcherModelList;
        private string path =@"E:\U8SOFT\ExcelModel";
        private RadioButton _DefaultRbtn;
        
        private void InitializeModelView()
        {
            this.VourcherModelList = XDocument.Load(path + "\\ModelList.xml");
            ModelListFilter(this.VourcherModelList);
            IEnumerable<XElement> source = VourcherModelList.Root.Elements("class");
            int num = source.Count();
            SuspendLayout();
            for (int i = 0; i < num; i++)
            {
                string value = source.ElementAt(i).Attribute("name").Value;
                string value2 = source.ElementAt(i).Attribute("id").Value;
                RadioButton radioButton = CreateRadioButton(value2, value);
                radioButton.Click += Rad_Click;
                if (_DefaultRbtn == null)
                {
                    _CurUserDefineRadBtn = (_DefaultRbtn = radioButton);
                }
                voucherClasses.Controls.Add(radioButton);
                if (i != num - 1)
                {
                    PictureBox pictureBox = new PictureBox();
                    pictureBox.Width = 25;
                    pictureBox.Height = 16;
                    pictureBox.Image = Yonyou.U8.QuickImport.Properties.Resources.pictureBox1;
                    voucherClasses.Controls.Add(pictureBox);
                }
            }
            ResumeLayout(false);
            this._table = new DataTable();
            this._table.Columns.Add("Selected", typeof(bool));
            this._table.Columns.Add("Name", typeof(string));
            this._table.Columns.Add("Path", typeof(string));
            this.itemGrid.Rows.Clear();
            this.itemGrid.DataSource = this._table.DefaultView;


        }
        
        private RadioButton _CurUserDefineRadBtn;
        
        private void Rad_Click(object sender, EventArgs e)
        {
            if (sender.GetType() != typeof(RadioButton))
            {
                return;
            }
            if (cBoxSolution.Checked)
            {
                string name = (sender as RadioButton).Name;
                string text = rBoxSolution.Text;
                if (!string.IsNullOrEmpty(text))
                {
                    LoadSolutionVourchers(text, name);
                    if (_Cache.ContainsKey(text))
                    {
                        _Cache[text] = sender;
                    }
                    else
                    {
                        _Cache.Add(text, sender);
                    }
                }
                else
                {
                    _table.Clear();
                }
            }
            else
            {
                string name2 = _CurUserDefineRadBtn.Name;
                SaveCheckedVourcherByUserDefine(name2);
                RadioButton radioButton = sender as RadioButton;
                name2 = radioButton.Name;
                LoadUserDefineVourchers(name2);
                _CurUserDefineRadBtn = radioButton;
            }
        }

        protected XDocument _FilePathUserDefineImportStrategy;
        
        private void LoadUserDefineVourchers(string className)
        {
            XElement xElement = VourcherModelList.XPathSelectElement("//class[@id='" + className + "']");
            ModelListFilter(xElement);
            _table.Rows.Clear();
            IEnumerable<XElement> enumerable = xElement.Elements();
            foreach (XElement item in enumerable)
            {
                if (!(item.Attribute("id").Value == "hrdts"))
                {
                    string value = item.Attribute("id").Value;
                    string value2 = item.Attribute("name").Value;
                    string value3 = item.Attribute("filename").Value;
                    bool flag = false;
                    string text = "";
                    if (_UserDefineImportStrategy.XPathSelectElement("//menu[@id='" + value + "']") != null)
                    {
                        flag = true;
                    }
                    text = ((_FilePathUserDefineImportStrategy.XPathSelectElement("//menu[@id='" + value + "']") == null) ? (path + "\\" + value3) : ((!(_FilePathUserDefineImportStrategy.XPathSelectElement("//menu[@id='" + value + "']").Attribute("modify").Value == "1")) ? (path + "\\" + value3) : _FilePathUserDefineImportStrategy.XPathSelectElement("//menu[@id='" + value + "']").Attribute("filename").Value));
                    _table.Rows.Add(flag, value2, text);
                }
            }
            if (_table.Rows.Count != 0)
            {
                CheckGridViewItemsSelectedState();
            }
        }


        protected XDocument _UserDefineImportStrategy;
        private void SaveCheckedVourcherByUserDefine(string className)
        {
            XElement xElement = _UserDefineImportStrategy.XPathSelectElement("//class[@id='" + className + "']");
            if (xElement == null)
            {
                return;
            }
            for (int i = 0; i < itemGrid.Rows.Count; i++)
            {
                string text = itemGrid.Rows[i].Cells["ColumnItem"].Value.ToString();
                string text2 = itemGrid.Rows[i].Cells["ColumnPath"].Value.ToString();
                bool flag = (bool)itemGrid.Rows[i].Cells["ColumnCheck"].Value;
                XElement xElement2 = xElement.XPathSelectElement(".//menu[@name='" + text + "']");
                if (xElement2 != null)
                {
                    xElement2.Remove();
                }
                if (!flag)
                {
                    continue;
                }
                XElement xElement3 = VourcherModelList.XPathSelectElement("//menu[@name='" + text + "']");
                XElement xElement4 = new XElement("menu");
                xElement4.SetAttributeValue("id", xElement3.Attribute("id").Value);
                xElement4.SetAttributeValue("name", xElement3.Attribute("name").Value);
                xElement4.SetAttributeValue("filename", text2);
                xElement.Add(xElement4);
                if (!cBoxSolution.Checked && (string.Compare(Path.GetExtension(text2), ".txt", true) == 0 || string.Compare(Path.GetExtension(text2), ".csv", true) == 0))
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(Path.Combine("E:\\U8soft\\", "ExcelModel\\ChildArch.xml"));
                    if (xmlDocument.SelectSingleNode("//arch[@name='" + text + "']") != null)
                    {
                        //FomrTxtChildArc fomrTxtChildArc = new FomrTxtChildArc(xElement3.Attribute("id").Value, text2, base.QIContext);
                        //fomrTxtChildArc.ShowDialog();
                    }
                }
            }
        }


        protected XDocument _ImportSolution;
        protected XDocument _FilePathImportSolution;
        private void LoadSolutionVourchers(string slnName, string className)
        {
            XElement xElement = VourcherModelList.XPathSelectElement("//class[@id='" + className + "']");
            ModelListFilter(xElement);
            if (xElement == null)
            {
                return;
            }
            _table.Clear();
            IEnumerable<XElement> enumerable = xElement.Elements();
            foreach (XElement item in enumerable)
            {
                if (!(item.Attribute("id").Value == "hrdts"))
                {
                    string value = item.Attribute("id").Value;
                    string value2 = item.Attribute("name").Value;
                    string value3 = item.Attribute("filename").Value;
                    bool flag = false;
                    string text = "";
                    if (_ImportSolution.XPathSelectElement("//menu[@id='" + value + "']") != null)
                    {
                        flag = true;
                    }
                    text = ((_FilePathImportSolution.XPathSelectElement("//menu[@id='" + value + "']") == null) ? (path + "\\" + value3) : ((!(_FilePathImportSolution.XPathSelectElement("//menu[@id='" + value + "']").Attribute("modify").Value == "1")) ? (path + "\\" + value3) : _FilePathImportSolution.XPathSelectElement("//menu[@id='" + value + "']").Attribute("filename").Value));
                    _table.Rows.Add(flag, value2, text);
                }
            }
            if (_table.Rows.Count != 0)
            {
                CheckGridViewItemsSelectedState();
            }
        }

        private void CheckGridViewItemsSelectedState()
        {
            headerCheckBox.KeyUp -= HeaderCheckBox_KeyUp;
            headerCheckBox.MouseClick -= HeaderCheckBox_MouseClick;
            headerCheckBox.Checked = true;
            int count = _table.Rows.Count;
            headerCheckBox.Checked = false;
            for (int i = 0; i < count; i++)
            {
                if (bool.Parse(_table.Rows[i]["Selected"].ToString()))
                {
                    headerCheckBox.Checked = true;
                    break;
                }
            }
            if (_table.Rows.Count == 0)
            {
                headerCheckBox.Checked = false;
            }
            headerCheckBox.KeyUp += HeaderCheckBox_KeyUp;
            headerCheckBox.MouseClick += HeaderCheckBox_MouseClick;
        }

        private RadioButton CreateRadioButton(string name, string text)
        {
            RadioButton radioButton = new RadioButton();
            radioButton.AutoSize = true;
            radioButton.Location = new Point(27, 232);
            radioButton.Name = name;
            radioButton.Size = new Size(47, 16);
            radioButton.TabIndex = 25;
            radioButton.TabStop = true;
            radioButton.Text = text;
            radioButton.UseVisualStyleBackColor = true;
            radioButton.ForeColor = Color.Black;
            return radioButton;
        }

        public static void ModelListFilter(XDocument xmlDoc)
        {
            IEnumerable<XElement> enumerable = xmlDoc.XPathSelectElements(".//menu");
            List<XElement> list = new List<XElement>();
            foreach (XElement item in enumerable)
            {
                XAttribute xAttribute = item.Attribute("support");
                if (xAttribute != null && !xAttribute.Value.ToUpper().Equals("QI"))
                {
                    list.Add(item);
                }
            }
            foreach (XElement item2 in list)
            {
                item2.Remove();
            }
        }

        public static void ModelListFilter(XElement element)
        {
            IEnumerable<XElement> enumerable = element.XPathSelectElements(".//menu");
            List<XElement> list = new List<XElement>();
            foreach (XElement item in enumerable)
            {
                XAttribute xAttribute = item.Attribute("support");
                if (xAttribute != null && !xAttribute.Value.ToUpper().Equals("QI"))
                {
                    list.Add(item);
                }
            }
            foreach (XElement item2 in list)
            {
                item2.Remove();
            }
        }

        private XDocument _SolutionList;

        private void InitializeImportStrategy()
        {
            _SolutionList = XDocument.Load(base.QIContext.QICurImportStrategy + "\\StrategyList.xml");
            IEnumerable<XElement> enumerable = _SolutionList.Root.Elements();
            foreach (XElement item in enumerable)
            {
                if (bool.Parse(item.Attribute("default").Value))
                {
                    cBoxSolution.Checked = true;
                    rBoxSolution.Text = item.Attribute("id").Value;
                    break;
                }
            }
        }

        private void InitializeVourcherView()
        {
            if (cBoxSolution.Checked)
            {
                string text = rBoxSolution.Text;
                _Cache.Add(text, _DefaultRbtn);
                LoadImportSolution(text + ".xml");
                LoadSolutionVourchers(text, _DefaultRbtn.Name);
                _DefaultRbtn.Checked = true;
            }
            else
            {
                string name = _CurUserDefineRadBtn.Name;
                LoadUserDefineStrategy();
                LoadUserDefineVourchers(name);
                _CurUserDefineRadBtn.Checked = true;
            }
        }

        private void InitializeEventHandler()
        {
            cBoxSolution.CheckedChanged += cBoxSolution_CheckedChanged;
        }

        private void cBoxSolution_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBox = sender as CheckBox;
            if (checkBox != null)
            {
                if (checkBox.Checked)
                {
                    SetItemGridReadOnly(true);
                    AdjustEnableState(ActionTiming.CheckedChange, true);
                    string text = (string.IsNullOrEmpty(rBoxSolution.Text) ? GetDefaultSolution() : rBoxSolution.Text);
                    RadioButton radioButton = _DefaultRbtn;
                    if (_Cache.ContainsKey(text))
                    {
                        radioButton = _Cache[text] as RadioButton;
                    }
                    if (string.IsNullOrEmpty(text))
                    {
                        _table.Clear();
                    }
                    else
                    {
                        rBoxSolution.Text = text;
                        LoadImportSolution(text + ".xml");
                        LoadSolutionVourchers(text, radioButton.Name);
                    }
                    radioButton.Checked = true;
                }
                else
                {
                    SetItemGridReadOnly(false);
                    AdjustEnableState(ActionTiming.CheckedChange, false);
                    string name = _CurUserDefineRadBtn.Name;
                    LoadUserDefineStrategy();
                    LoadUserDefineVourchers(name);
                    _CurUserDefineRadBtn.Checked = true;
                }
            }
            tBoxFocus.Focus();
        }

        private void SetItemGridReadOnly(bool readOnly)
        {
            headerCheckBox.Visible = !readOnly;
            itemGrid.ReadOnly = readOnly;
        }
        private void AdjustEnableState(ActionTiming actionTime, params object[] args)
        {
            switch (actionTime)
            {
                case ActionTiming.Init:
                    {
                        bool flag = (bool)args[0];
                        bool itemGridReadOnly = flag;
                        SetItemGridReadOnly(itemGridReadOnly);
                        AdjustInitEnableState(flag);
                        break;
                    }
                case ActionTiming.CheckedChange:
                    AdjustImportStrategyChangeEnableState((bool)args[0]);
                    break;
            }
        }

        private enum ActionTiming
        {
            Init = 0,
            CheckedChange = 1
        }

        private void AdjustInitEnableState(bool isSolution)
        {
            if (isSolution)
            {
                rBoxSolution.Visible = true;
                btnSolutionManager.Visible = true;
                btnRestore.Visible = false;
            }
            else
            {
                rBoxSolution.Visible = false;
                btnSolutionManager.Visible = false;
                btnRestore.Visible = true;
            }
            if (!CommonUtil.CheckAuthValid(base.QIContext.Login, "QI0105"))
            {
                btnSolutionManager.Visible = false;
                btnSolutionManager.Tag = false;
            }
        }

        private void AdjustImportStrategyChangeEnableState(bool isSolution)
        {
            if (isSolution)
            {
                rBoxSolution.Visible = true;
                btnRestore.Visible = false;
                if (btnSolutionManager.Tag == null || (bool)btnSolutionManager.Tag)
                {
                    btnSolutionManager.Visible = true;
                }
            }
            else
            {
                rBoxSolution.Visible = false;
                btnSolutionManager.Visible = false;
                btnRestore.Visible = true;
            }
        }

        protected void LoadUserDefineStrategy()
        {
            if (_UserDefineImportStrategy == null)
            {
                _UserDefineImportStrategy = XDocument.Load(base.QIContext.QICurImportStrategy + "\\DefaultImportStrategy.xml");
            }
            if (_FilePathUserDefineImportStrategy == null)
            {
                _FilePathUserDefineImportStrategy = XDocument.Load(base.QIContext.QICurImportStrategyFilePath + "\\DefaultImportStrategy.xml");
            }
        }

        protected void LoadImportSolution(string fileName)
        {
            _ImportSolution = XDocument.Load(base.QIContext.QICurImportStrategy + "\\" + fileName);
            _FilePathImportSolution = XDocument.Load(base.QIContext.QICurImportStrategyFilePath + "\\" + fileName);
        }

        private string GetDefaultSolution()
        {
            _SolutionList = XDocument.Load(base.QIContext.QICurImportStrategy + "\\StrategyList.xml");
            string text = string.Empty;
            foreach (XElement item in _SolutionList.Root.Elements())
            {
                string value = item.Attribute("id").Value;
                string value2 = item.Attribute("default").Value;
                bool flag = !string.IsNullOrEmpty(value2) && bool.Parse(value2);
                if (!string.IsNullOrEmpty(value))
                {
                    if (flag)
                    {
                        return value;
                    }
                    if (string.IsNullOrEmpty(text))
                    {
                        text = value;
                    }
                }
            }
            return text;
        }

        private void GridContainer_ClientSizeChanged(object sender, EventArgs e)
        {
            itemGrid.Height = GridContainer.ClientSize.Height - 5;
            itemGrid.Width = GridContainer.ClientSize.Width - itemGrid.Location.X;
            itemGrid.Columns["ColumnPath"].Width = itemGrid.Width - itemGrid.Columns["ColumnCheck"].Width - itemGrid.Columns["ColumnItem"].Width - itemGrid.Location.X;
        }

        private void itemGrid_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!itemGrid.ReadOnly && e.RowIndex >= 0 && e.RowIndex <= itemGrid.Rows.Count - 1 && !(itemGrid.Columns[e.ColumnIndex].Name != "ColumnPath"))
            {
                openFileDlg.InitialDirectory = Path.GetDirectoryName(itemGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                openFileDlg.FileName = Path.GetFileName(itemGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                openFileDlg.Filter = "电子表格文档(*.xls)|*.xls|逗号分隔文档(*.csv)|*.csv|文本文档(*.txt)|*.txt|所有文档(*.*)|*.*";
                if (openFileDlg.ShowDialog() == DialogResult.OK)
                {
                    itemGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = openFileDlg.FileName;
                    itemGrid.AutoResizeColumn(e.ColumnIndex);
                    ChangeFilePath(itemGrid.Rows[e.RowIndex].Cells["ColumnItem"].Value.ToString(), openFileDlg.FileName);
                }
                tBoxFocus.Focus();
            }
        }

        private void ChangeFilePath(string Id, string FilePath)
        {
            if (_FilePathUserDefineImportStrategy.XPathSelectElement("//menu[@name='" + Id + "']") != null)
            {
                _FilePathUserDefineImportStrategy.XPathSelectElement("//menu[@name='" + Id + "']").Attribute("modify").Value = "1";
                _FilePathUserDefineImportStrategy.XPathSelectElement("//menu[@name='" + Id + "']").Attribute("filename").Value = FilePath;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (SaveImportStrategy())
            {
                Import();
            }
        }

        private void Import()
        {
            //InitMultiLangRes();
            try
            {
                if (base.QIContext.Login == null)
                {
                    UFSoft.U8.Framework.Login.UI.clsLogin clsLogin = new UFSoft.U8.Framework.Login.UI.clsLogin();
                    if (!clsLogin.login("DP"))
                    {
                        MessageBox.Show("登录失败!" + clsLogin.ErrDescript);
                        return;
                    }
                    clsLoginClass clsLoginClass = new clsLoginClass();
                    if (!clsLoginClass.ConstructLogin(clsLogin.userToken))
                    {
                        throw new ApplicationException(clsLoginClass.ShareString);
                    }
                    string pSubId = "DP";
                    string pAccId = string.Empty;
                    string pYearId = string.Empty;
                    string pUserId = string.Empty;
                    string pPassword = "";
                    string pDate = string.Empty;
                    string cSrv = string.Empty;
                    string cSerial = "";
                    if (!clsLoginClass.Login(ref pSubId, ref pAccId, ref pYearId, ref pUserId, ref pPassword, ref pDate, ref cSrv, ref cSerial))
                    {
                        throw new ApplicationException(clsLoginClass.ShareString);
                    }
                    base.QIContext.Login = clsLoginClass;
                }
                string[] array = new string[2];
                Type typeFromProgID = Type.GetTypeFromProgID("U8Common.iCommon");
                if (typeFromProgID == null)
                {
                    MessageBox.Show("系统未注册组件U8Common.iCommon");
                    return;
                }
                object target = typeFromProgID.InvokeMember(null, BindingFlags.DeclaredOnly 
                    | BindingFlags.Instance 
                    | BindingFlags.Public 
                    | BindingFlags.NonPublic 
                    | BindingFlags.CreateInstance, null, null, null);
                array[0] = base.QIContext.Login.UfMetaName;
                array[1] = base.QIContext.Login.UfDbName;
                typeFromProgID.InvokeMember("SetConnectionWithConnString", BindingFlags.DeclaredOnly 
                    | BindingFlags.Instance 
                    | BindingFlags.Public 
                    | BindingFlags.NonPublic 
                    | BindingFlags.InvokeMethod, null, target, array);
                XmlDocument xmlDocument = CommonUtil.ReadStrategy(cBoxSolution.Checked, true, base.QIContext);
                if (xmlDocument == null)
                {
                    return;
                }
                XmlNode xmlNode = xmlDocument.SelectSingleNode("/data/import");
                if (xmlNode == null)
                {
                    return;
                }
                string text = "";
                XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//class/menu");
                foreach (XmlNode item in xmlNodeList)
                {
                    text = text + item.Attributes["name"].InnerText + ",";
                }
                if (text.Length > 0)
                {
                    text = text.Substring(0, text.Length - 1);
                }
                if (xmlNode.Attributes["type"].InnerText == "4")
                {
                    string text2 = "";
                    if (MessageBox.Show(text: (text.Length != 0) ? ("清空操作将删除产品中所有数据！包括本工具导入的数据和非本工具导入的数据！是否确定清空下列档案:" + text) : "清空操作将删除产品中所有数据！包括本工具导入的数据和非本工具导入的数据！是否确定执行清空操作?", owner: base.QIContext.FrmMdiParent, caption: "清空", buttons: MessageBoxButtons.YesNo, icon: MessageBoxIcon.Exclamation) == DialogResult.No)
                    {
                        return;
                    }
                }
                DataImport dataImport = new DataImport(base.QIContext);
                string querytoken = "";
                bool flag = dataImport.transimport(xmlDocument.OuterXml, base.QIContext.Login, ref querytoken, base.QIContext.FrmMdiParent);
                string caption = "";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                TabPage tapPage;
                if (!base.QIContext.CheckTab("tpImportLog", out tapPage))
                {
                    return;
                }
                DialogResult dialogResult = ((!flag) ? MessageBox.Show(base.QIContext.TabContainer, "本次导入有部分错误，是否查看本次的导入日志?", caption, buttons, MessageBoxIcon.Question) : MessageBox.Show(base.QIContext.TabContainer, "本次导入全部成功，是否查看本次的导入日志?", caption, buttons, MessageBoxIcon.Question));
                if (dialogResult == DialogResult.Yes)
                {
                    QueryLog queryLog = null;
                    if (tapPage != null)
                    {
                        queryLog = ImportPanel.Query(tapPage, base.QIContext) as QueryLog;
                    }
                    if (queryLog != null)
                    {
                        queryLog.QueryToken(" where token='" + querytoken + "'");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(base.QIContext.TabContainer, ex.Message);
            }
        }

        private void InitMultiLangRes()
        {
            //if (bInitRes)
            //{
            //    return;
            //}
            try
            {
                //if (resSrv == null)
                //{
                //    resSrv = new ResourceServiceWrapper();
                //}
                //if (resFactory == null)
                //{
                //    resFactory = new ResourceServiceFactoryClass();
                //}
                //resSrv.Init("");
                //int num = 0;
                //resFactory.SetResourceType(ref num);
                //string text = "zh-CN";
                //localSrv = resFactory.GetLocalService();
                //localSrv.SetProcessLocalID(ref text);
                //bInitRes = true;
            }
            catch (Exception)
            {
                throw new Exception("初始化U8多语服务失败，请确认正确安装了U8ERP！");
            }
        }

        private bool SaveImportStrategy()
        {
            try
            {
                if (!cBoxSolution.Checked)
                {
                    string name = _CurUserDefineRadBtn.Name;
                    SaveCheckedVourcherByUserDefine(name);
                    if (SevParaIsEmpty() && !CanEmpty())
                    {
                        return false;
                    }
                    if (SevParaIsDiffEdit() && !CanDiffEdit())
                    {
                        return false;
                    }
                    XElement xElement = _UserDefineImportStrategy.XPathSelectElement("//import");
                    xElement.Attributes().ElementAt(1).Value = Context.QIPath + "\\log\\";
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(base.QIContext.QICurImportStrategy + "\\DefaultImportStrategy.xml", null);
                    _UserDefineImportStrategy.Save(xmlTextWriter);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    xmlTextWriter = new XmlTextWriter(base.QIContext.QICurImportStrategyFilePath + "\\DefaultImportStrategy.xml", null);
                    _FilePathUserDefineImportStrategy.Save(xmlTextWriter);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    SaveSolutionList(false);
                }
                else
                {
                    SaveSolutionList(true);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入策略保存失败！" + ex.Message);
            }
            return false;
        }

        private bool SevParaIsEmpty()
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(Context.QIPath + "\\ImportStrategy\\ImportParameter.xml");
            XmlNode xmlNode = xmlDocument.SelectSingleNode("//import");
            if (xmlNode.Attributes["type"].InnerText == "4")
            {
                return true;
            }
            return false;
        }

        private bool CanEmpty()
        {
            Hashtable hashtable = ReadConfig();
            ArrayList arrayList = ReadEmptyServer();
            for (int i = 0; i < arrayList.Count; i++)
            {
                if (hashtable.ContainsKey(arrayList[i]))
                {
                    hashtable.Remove(arrayList[i]);
                }
            }
            if (hashtable.Count > 0)
            {
                string[] array = new string[hashtable.Count];
                hashtable.Values.CopyTo(array, 0);
                for (int j = 0; j < array.Length; j++)
                {
                    array[j] = "\"" + array[j] + "\"";
                }
                if (cBoxSolution.Checked)
                {
                    if (MessageBox.Show(this, string.Concat("下列档案不提供清空服务：", string.Concat(array), "\n是否继续？"), "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string filename = base.QIContext.QICurImportStrategy + "\\" + rBoxSolution.Text + ".xml";
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.Load(filename);
                        foreach (object key in hashtable.Keys)
                        {
                            XmlNode xmlNode = xmlDocument.SelectSingleNode("//menu[@id='" + key.ToString() + "']");
                            xmlNode.ParentNode.RemoveChild(xmlNode);
                        }
                        xmlDocument.Save(filename);
                        return true;
                    }
                }
                else
                {
                    MessageBox.Show(this, string.Concat("下列档案不提供清空服务：", string.Concat(array)));
                }
                return false;
            }
            return true;
        }

        private Hashtable ReadConfig()
        {
            Hashtable hashtable = new Hashtable();
            IEnumerable<XElement> enumerable;
            if (cBoxSolution.Checked)
            {
                XDocument node = XDocument.Load(base.QIContext.QICurImportStrategy + "\\" + rBoxSolution.Text + ".xml");
                enumerable = node.XPathSelectElements("//menu");
            }
            else
            {
                enumerable = _UserDefineImportStrategy.XPathSelectElements("//menu");
            }
            foreach (XElement item in enumerable)
            {
                string value = item.Attribute("id").Value;
                string value2 = item.Attribute("name").Value;
                hashtable.Add(value, value2);
            }
            return hashtable;
        }

        private ArrayList ReadEmptyServer()
        {
            ArrayList arrayList = new ArrayList();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(Context.QIPath + "\\Xml\\ImportConfig.xml");
            XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//ServerRegion/*[@empty='true']");
            foreach (XmlNode item in xmlNodeList)
            {
                arrayList.Add(item.Name);
            }
            return arrayList;
        }

        private bool SevParaIsDiffEdit()
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(Context.QIPath + "\\ImportStrategy\\ImportParameter.xml");
            XmlNode xmlNode = xmlDocument.SelectSingleNode("//import");
            if (xmlNode.Attributes["type"].InnerText == "5")
            {
                return true;
            }
            return false;
        }

        private bool CanDiffEdit()
        {
            Hashtable hashtable = ReadConfig();
            ArrayList arrayList = ReadDiffEditServer();
            for (int i = 0; i < arrayList.Count; i++)
            {
                if (hashtable.ContainsKey(arrayList[i]))
                {
                    hashtable.Remove(arrayList[i]);
                }
            }
            if (hashtable.Count > 0)
            {
                string[] array = new string[hashtable.Count];
                hashtable.Values.CopyTo(array, 0);
                for (int j = 0; j < array.Length; j++)
                {
                    array[j] = "\"" + array[j] + "\"";
                }
                if (cBoxSolution.Checked)
                {
                    if (MessageBox.Show(this, string.Concat("下列档案不提供差异更新服务：", string.Concat(array), "\n是否继续？"), "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        string filename = base.QIContext.QICurImportStrategy + "\\" + rBoxSolution.Text + ".xml";
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.Load(filename);
                        foreach (object key in hashtable.Keys)
                        {
                            XmlNode xmlNode = xmlDocument.SelectSingleNode("//menu[@id='" + key.ToString() + "']");
                            xmlNode.ParentNode.RemoveChild(xmlNode);
                        }
                        xmlDocument.Save(filename);
                        return true;
                    }
                }
                else
                {
                    MessageBox.Show(this, string.Concat("下列档案不提供差异更新服务：", string.Concat(array)));
                }
                return false;
            }
            return true;
        }

        private ArrayList ReadDiffEditServer()
        {
            ArrayList arrayList = new ArrayList();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(Context.QIPath + "\\Xml\\ImportConfig.xml");
            XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//ServerRegion/*[@diffEdit='true']");
            foreach (XmlNode item in xmlNodeList)
            {
                arrayList.Add(item.Name);
            }
            return arrayList;
        }

        private void SaveSolutionList(bool isInSolution)
        {
            IEnumerable<XElement> enumerable = _SolutionList.Root.Elements();
            foreach (XElement item in enumerable)
            {
                if (isInSolution && item.Attribute("id").Value.Equals(rBoxSolution.Text))
                {
                    item.Attribute("default").Value = "true";
                }
                else
                {
                    item.Attribute("default").Value = "false";
                }
            }
            XmlTextWriter xmlTextWriter = new XmlTextWriter(base.QIContext.QICurImportStrategy + "\\StrategyList.xml", null);
            _SolutionList.Save(xmlTextWriter);
            xmlTextWriter.Flush();
            xmlTextWriter.Close();
        }



    }
}
